package com.yizhubao.app.customviews;

import android.content.Context;
import android.os.CountDownTimer;
import android.util.AttributeSet;

import androidx.appcompat.widget.AppCompatTextView;

import com.yizhubao.app.R;

/**
 * 创建人: PACY
 * 创建时间: 6/8/21 8:44 AM
 * 邮箱: pengwwe457621023@qq.com
 * 类描述: 验证码倒计时
 */
public class VerificationCodeText extends AppCompatTextView {
    private long length = 60 * 1000;// 倒计时长度，默认一分钟
    private String textBefore = "获取";
    private int textColor;

    private CountDownTimer countDownTimer ;

    public VerificationCodeText(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        textColor = getCurrentTextColor();
    }

    /**
     * 设置到计时长度,时间 默认毫秒
     *
     * @return
     */
    public void setLenght(long length) {
        this.length = length;
    }


    /**
     * 开始
     */
    public void start() {
        setEnableType(false);
        if(countDownTimer==null){
            countDownTimer = new CountDownTimer(length, 1000) {
                @Override
                public void onTick(long millisUntilFinished) {
                    String str = (millisUntilFinished / 1000 )+1+ "S";
                    setText(str);
                }

                @Override
                public void onFinish() {
                    setEnableType(true);
                    setText("获取");
                }
            };
        }

        countDownTimer.start();
    }

    public void setEnableType(boolean enable){
        if(enable){
            setTextColor(textColor);
        }else{
            setTextColor(getResources().getColor(R.color.enableColor));
        }
        setEnabled(enable);
    }

    /**
     * 停止
     */
    public void stop() {
        countDownTimer.onFinish();
        setText(textBefore);
    }
}
